package gl.android.biyiqing.competent;

import gl.android.biyiqing.MessageBoxActivity;
import gl.android.biyiqing.api.API;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.Lg;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

public class UnreadMessageTextview {

	private TextView tv;
	private Handler handler;
	private boolean isRuning;

	public UnreadMessageTextview(TextView view) {
		this.tv = view;
		tv.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setHasRead();
				Intent intent = new Intent(v.getContext(),
						MessageBoxActivity.class);
				v.getContext().startActivity(intent);
				
			}
		});
		this.handler = new Handler();
	}

	public void start() {
		if (isRuning) {
			Lg.e("unreadmessage is running");
			return;
		}
		handler.post(new Runnable() {
			@Override
			public void run() {
				BaseControl.get(API.URL + "GetUnreadMessage?userid=%s",
						new AjaxCallBack<String>() {
							@Override
							public void onSuccess(String t) {
								super.onSuccess(t);
								try {
									String unread = new JSONObject(t)
											.getString("msg");

									if (Integer.parseInt(unread) <= 0) {
										tv.setVisibility(View.GONE);
									} else {
										tv.setVisibility(View.VISIBLE);
										tv.setText(unread);
										tv.startAnimation(AnimationUtils
												.loadAnimation(tv.getContext(),
														android.R.anim.fade_in));

									}
								} catch (Exception e) {
									Lg.e(e.getMessage());
//									e.printStackTrace();
								}
							}
						}, new Object[] { UserManger.getInstance().userid });
				handler.postDelayed(this, 30 * 1000);
			}
		});
		isRuning = true;
	}

	public void setHasRead() {
		tv.setVisibility(View.GONE);
		tv.setText("");
		tv.startAnimation(AnimationUtils.loadAnimation(tv.getContext(),
				android.R.anim.fade_out));
	}

	public void stop() {
		isRuning = false;
		handler.removeCallbacksAndMessages(null);
	};
}
